package com.lambert.young.im.handler;

import com.alibaba.fastjson2.JSON;
import com.lambert.young.im.command.Command;
import com.lambert.young.im.command.CommandType;
import com.lambert.young.im.command.Result;
import com.lambert.young.im.command.ResultType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>WebSocketHandler </p>
 *
 * @author liubaolin
 * @since 2024/10/31 11:31 AM
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
        try{
            log.info(frame.text());
            Command command = JSON.parseObject(frame.text(),Command.class);
            switch (CommandType.match(command.getCode())){
                case CONNECTION -> ConnectionHandler.execute(ctx,command);
                case CHAT -> ChatHandler.execute(ctx,frame);
                case JOIN_GROUP -> JoinGroupHandler.execute(ctx);
                case GET_ONLINE_USERS -> OnlineUsersHandler.execute(ctx);
                default -> ctx.channel().writeAndFlush(Result.fail(ResultType.NOT_SUPPORTED_CODE.getMessage()));
            }
        }catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail(ResultType.BASIC_ERROR.getMessage()));
        }
    }
}
